<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-11-06
 * Time: 16:11
 */

namespace app\admin\controller;


use app\constant\ActivesConst;
use app\constant\TenantConst;
use app\model\AdminActives;
use app\model\AdminTenant;
use app\util\ReturnCode;
use think\Exception;
use think\facade\Cache;
use think\facade\Log;

class Common extends Base
{
    /**
     * 用于更新redis中缓存的浏览量数据到数据库中，通过在3：00通过定时任务执行一次
     */
    public function updateCacheView()
    {
        $key = $this->request->param('key');
        if ($key !== config('apiadmin.UPDATE_VIEWS_KEY')) {
            return;
        } else {
            $cache = Cache::init();
            // 获取缓存对象句柄
            $handler = $cache->handler();
            $prefix = config('cache.prefix') . ActivesConst::VIEWS_TAG;
            $keys = $handler->keys($prefix . '*');
            if ($keys && count($keys) > 0) {
                foreach ($keys as $key) {
                    //将原来的缓存清除
                    $views = $handler->get($key);
                    $handler->del($key);
                    //获取到真实的活动id
                    $id = str_ireplace($prefix, "", $key);
                    try {
                        //更新浏览数
                        (new AdminActives())->where(['id' => $id])->setInc('views', $views);
                    } catch (Exception $e) {
                        Log::error('views_cache_update_failed_' . $id);
                    }
                }
            }
        }
    }

    /**
     * 更新会员到期的站点的状态
     */
    public function updateTenantStatus()
    {
        $key = $this->request->param('key');
        if ($key !== config('apiadmin.UPDATE_VIEWS_KEY')) {
            echo '非法请求，已记录当前ip';
        } else {
            $todayStart = date('Y-m-d 00:00:00', time());
            try {
                $tenants = (new AdminTenant())->where(['status'=>TenantConst::STATUS_NORMAL])->whereTime('expiration_time', '<=', $todayStart)->field('id,status')
                    ->select();
                $update = [];
                if ($tenants && count($tenants) > 0) {
                    foreach ($tenants as $item) {
                        $update[] = ['id'=>$item['id'],'status'=>TenantConst::STATUS_EXPIRATION];
                    }
                }
                $model = new AdminTenant();
                $result = $model->saveAll($update,true);
                if (!$result) {
                    throw new \Exception();
                }
                return $this->buildSuccess('success');
            } catch (\Exception $e) {
                Log::error('更新站点过期状态失败');
                return $this->buildFailed(ReturnCode::FAILED,'failed');
            }
        }
    }
}